import 'dart:io';
import 'package:flutter_logger_server/flutter_logger_server_platform_interface.dart';
import 'package:flutter_logger_server/plugins/http_logger_plugin.dart';
import 'package:flutter_logger_server/utils/log_utils.dart';
import 'package:flutter_logger_server/utils/webserver_utils.dart';
import 'package:flutter_logger_server/utils/websocket_utils.dart';
import 'plugins/message_logger_plugin.dart';

class FlutterLoggerServer {
  HttpServer? _htmlWebServer;
  final HttpLoggerPlugin _httpLoggerPlugin = HttpLoggerPlugin();
  final MessageLoggerPlugin _messageLoggerPlugin = MessageLoggerPlugin();
  WebSocketUtils webSocketUtils = WebSocketUtils();
  String? webSocketUrl = "";
  bool isStarted = false;
  bool isDebug = true;
  static FlutterLoggerServer? _instance;

  static FlutterLoggerServer get instance => _instance ??= FlutterLoggerServer();

  HttpLoggerPlugin get httpLoggerPlugin => _httpLoggerPlugin; //单实例
  MessageLoggerPlugin get messageLoggerPlugin => _messageLoggerPlugin; //单实例
  Future<String?> getPlatformVersion() {
    return FlutterLoggerServerPlatform.instance.getPlatformVersion();
  }
  String? getWebSocketUrl() {
    return webSocketUrl;
  }

  void setDebug(bool isDebug) {
    this.isDebug = isDebug;
  }

  Future<void> startServer() async {
    _httpLoggerPlugin.init();
    try {
      final s = await HttpServer.bind(InternetAddress.anyIPv4, 9999, shared: false);
      s.listen(WebServerUtils.handleReq);

      _htmlWebServer = s;
      webSocketUtils.init();
      isStarted = true;
    } catch (e) {
      stopServer();
      LogUtils.log('Error starting server: $e');
    }
  }

  void stopServer() {
    _htmlWebServer?.close();
    webSocketUtils.close();
    isStarted = false;
    _httpLoggerPlugin.clear();
  }

  /// 构建cURL命令的函数
// String dioRequestToCurl(RequestOptions requestOptions) {
//   String method = requestOptions.method.toUpperCase();
//   String url = requestOptions.uri.toString();
//
//   // 添加请求方法和URL
//   String curlCmd = "curl -X $method '$url'";
//
//   // 添加请求头
//   requestOptions.headers.forEach((key, value) {
//     curlCmd += " -H '$key: $value'";
//   });
//
//   // 处理请求体
//   if (requestOptions.data != null) {
//     if (requestOptions.data is Map || requestOptions.data is List) {
//       String jsonData = jsonEncode(requestOptions.data);
//       curlCmd += " -d '$jsonData'";
//     } else if (requestOptions.data is String) {
//       curlCmd += " -d '${requestOptions.data}'";
//     }
//   }
//
//   return curlCmd;
// }
}
